<template>
  <div class="book-detail-page">
    <BookDetailHeader
      v-if="book"
      :book="book"
      :navigator-collapsed="navigatorCollapsed"
      :mobile="isMobile"
      @read-first="goFirstChapter"
      @toggle-outline="toggleNavigator"
    />

    <div v-else class="loading-head">
      <el-skeleton :rows="4" animated />
    </div>

    <div class="layout" :class="{ 'nav-open': !navigatorCollapsed && isMobile }">
      <!-- Desktop / wide: 固定侧栏；Mobile: 抽屉 -->
      <transition name="slide-x">
        <ChapterNavigator
          v-show="!navigatorCollapsed"
          class="navigator-wrapper"
          :class="{ 'as-drawer': isMobile }"
          :chapters="chapters"
            :active-chapter-id="activeChapterId"
          :active-section-index="activeSectionIndex"
          :collapsed="false"
          @select="handleSelectChapter"
          @select-section="handleSelectSection"
          @close="closeNavigator"
        />
      </transition>
      <transition name="fade-fast">
        <div
          v-if="isMobile && !navigatorCollapsed"
          class="nav-overlay"
          @click="closeNavigator"
        />
      </transition>

      <ReadingPane
        :chapter="currentChapterData"
        :all-chapters="showAll ? chapters : null"
        :scroll-to="scrollTarget"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useBooksStore } from '@/store/books'
import BookDetailHeader from '@/components/book/BookDetailHeader.vue'
import ChapterNavigator from '@/components/book/ChapterNavigator.vue'
import ReadingPane from '@/components/book/ReadingPane.vue'

const route = useRoute()
const router = useRouter()
const booksStore = useBooksStore()

const navigatorCollapsed = ref(false) // Desktop: false=显示, true=隐藏; Mobile: false=抽屉打开, true=关闭
const isMobile = ref(false)
const bookId = Number(route.params.bookId)
const currentChapterData = ref(null)
const showAll = ref(false)
const activeSectionIndex = ref(null)
const scrollTarget = ref(null) // { chapterId, sectionIndex, paragraphIndex? }

const book = computed(() => booksStore.detailMap[bookId])
const chapters = computed(() => book.value?.content?.chapters || [])
const activeChapterId = computed(() => booksStore.activeChapterId)

async function ensureDetail() {
  await booksStore.ensureBookDetail(bookId)
  booksStore.setActiveBook(bookId)
}

async function handleSelectChapter(chapterId, opts = {}) {
  booksStore.setActiveChapter(chapterId)
  showAll.value = false
  // 若未来支持按需加载，可在这里调用章节加载 API；当前 detail 已包含完整章节
  const ch = chapters.value.find(c => c.id === chapterId)
  currentChapterData.value = ch || null
  // 默认行为：切换章节时重置到第一节，除非显式保持滚动
  if (opts.preserveScroll) {
    // 保持现有 section/paragraph 目标
  } else {
    const hasSections = ch && Array.isArray(ch.sections) && ch.sections.length > 0
    activeSectionIndex.value = hasSections ? 0 : null
    // 设置新的滚动目标（第一节）
    if (hasSections) {
      scrollTarget.value = { chapterId, sectionIndex: 0, paragraphIndex: undefined, ts: Date.now() }
    } else {
      scrollTarget.value = null
    }
  }
  // 构造新的 query：不保留旧 p，若需要默认第一节则写 p=0
  const nextQuery = { ...route.query, chapter: chapterId }
  if (opts.preserveScroll) {
    // 保留原有 p（由外部逻辑决定）
  } else {
    delete nextQuery.p
    if (activeSectionIndex.value === 0) nextQuery.p = '0'
  }
  router.replace({ params: { bookId: bookId }, query: nextQuery })
  await nextTick()
}

async function handleSelectSection(payload) {
  const { chapterId, sectionIndex, paragraphIndex } = payload
  if (!currentChapterData.value || currentChapterData.value.id !== chapterId) {
    await handleSelectChapter(chapterId, { preserveScroll: true })
  }
  activeSectionIndex.value = sectionIndex
  scrollTarget.value = { chapterId, sectionIndex, paragraphIndex, ts: Date.now() }
  const p = typeof paragraphIndex === 'number' ? `${sectionIndex}-${paragraphIndex}` : `${sectionIndex}`
  router.replace({ params: { bookId: bookId }, query: { ...route.query, chapter: chapterId, p } })
}

function goFirstChapter() {
  if (chapters.value.length) {
    handleSelectChapter(chapters.value[0].id)
  }
}

function toggleNavigator() {
  // Mobile: 打开/关闭抽屉；Desktop: 隐藏/显示目录
  navigatorCollapsed.value = !navigatorCollapsed.value
}
function closeNavigator() { navigatorCollapsed.value = true }

function handleResize() {
  isMobile.value = window.innerWidth < 980
  // 切回桌面模式时强制显示目录
  if (!isMobile.value) navigatorCollapsed.value = false
}

// 路由变化 -> 解析并定位
watch(
  () => [route.query.chapter, route.query.p, chapters.value.length],
  async (vals) => {
    const [chapterQ, pQ, len] = vals
    if (!chapterQ || !len) return
    const cid = Number(chapterQ)
    if (isNaN(cid)) return
    await handleSelectChapter(cid, { preserveScroll: true })
    if (pQ) {
      const parts = String(pQ).split('-').map(n => Number(n))
      if (parts.length >= 1 && !parts.some(isNaN)) {
        const sectionIndex = parts[0]
        const paragraphIndex = parts.length > 1 ? parts[1] : undefined
        // 使用时间戳确保 watch 触发
        scrollTarget.value = { chapterId: cid, sectionIndex, paragraphIndex, ts: Date.now() }
        activeSectionIndex.value = sectionIndex
      }
    }
  },
  { immediate: false }
)

onMounted(async () => {
  handleResize()
  window.addEventListener('resize', handleResize, { passive: true })
  await ensureDetail()
  // 等待章节数据 ready 后再触发一次路由解析
  if (route.query.chapter) {
    // 强制触发 watch（chapters length 变化会调用）
    if (chapters.value.length) {
      const cid = Number(route.query.chapter)
      if (!isNaN(cid)) {
        await handleSelectChapter(cid, { preserveScroll: true })
        if (route.query.p) {
          const parts = String(route.query.p).split('-').map(n => Number(n))
          if (parts.length >= 1 && !parts.some(isNaN)) {
            const sectionIndex = parts[0]
            const paragraphIndex = parts.length > 1 ? parts[1] : undefined
            scrollTarget.value = { chapterId: cid, sectionIndex, paragraphIndex, ts: Date.now() }
            activeSectionIndex.value = sectionIndex
          }
        }
      }
    }
  }
})

onUnmounted(() => { window.removeEventListener('resize', handleResize) })
</script>

<style scoped>
/* 背景优化：宣纸质感 + 柔金渐层 */
.book-detail-page { padding: 0 40px 120px; min-height:100vh; position:relative; background:
  radial-gradient(circle at 18% 20%, rgba(255,255,255,0.65), transparent 60%),
  radial-gradient(circle at 82% 70%, rgba(255,255,255,0.5), transparent 65%),
  linear-gradient(135deg,#f6f1e9 0%,#efe5d6 55%,#e6dac8 100%);
  background-blend-mode:overlay,overlay,normal;
}
.book-detail-page::after { content:''; position:absolute; inset:0; pointer-events:none; background:repeating-linear-gradient(45deg,rgba(255,255,255,0.25) 0 10px,rgba(0,0,0,0.015) 10px 20px); mix-blend-mode:soft-light; opacity:.8; }
.loading-head { padding:40px 0; }
 .layout { display:flex; gap:34px; align-items:stretch; position:relative; }
 .layout:not(.nav-open) { transition: gap .25s ease; }
 .layout .reading-pane { flex:1; }
 /* 当桌面模式且目录隐藏时，正文自然充满（无需额外样式，只保证导航被移除即可） */
.layout.nav-open { overflow:hidden; }
 .navigator-wrapper.as-drawer { position:fixed; top:70px; left:0; bottom:0; width:270px; z-index:60; }
 .nav-overlay { position:fixed; inset:0; background:rgba(0,0,0,0.38); backdrop-filter:blur(2px); z-index:50; }
 .slide-x-enter-active, .slide-x-leave-active { transition: transform .32s cubic-bezier(.4,0,.2,1), opacity .32s; }
 .slide-x-enter-from, .slide-x-leave-to { transform: translateX(-120%); opacity:0; }
 .fade-fast-enter-active, .fade-fast-leave-active { transition: opacity .25s ease; }
 .fade-fast-enter-from, .fade-fast-leave-to { opacity:0; }
@media (max-width: 1280px) { .layout { gap:20px; } }
@media (max-width: 980px) { .layout { flex-direction:column; } }
/* 暗色模式 */
@media (prefers-color-scheme: dark){
  .book-detail-page { background:
    radial-gradient(circle at 18% 20%, rgba(255,255,255,0.08), transparent 60%),
    radial-gradient(circle at 82% 70%, rgba(255,255,255,0.06), transparent 65%),
    linear-gradient(135deg,#2f2924 0%,#3a332c 55%,#443a30 100%);
  }
  .book-detail-page::after { background:repeating-linear-gradient(45deg,rgba(255,255,255,0.08) 0 10px,rgba(0,0,0,0.18) 10px 20px); opacity:.55; }
}
</style>
